package net.xdclass.springboot.domain;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.message.MapMessage;
import org.slf4j.*;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

@RestControllerAdvice
public class CustomExtHandler {

    private static final Logger logger = LoggerFactory.getLogger(CustomExtHandler.class);

    @ExceptionHandler(value = Exception.class)
//    @ResponseBody
    Object handleException(Exception e, HttpServletRequest request){
        HashMap param = new HashMap();
        param.put("code", 5000);
        param.put("msg", e.getMessage());
        param.put("uri", request.getRequestURI());
        param.put("url", request.getRequestURL());
        // 使用 MapMessage 将 HashMap 转换为 JSON 格式
        MapMessage mapMessage = new MapMessage();
        mapMessage.putAll(param);
        logger.error(String.valueOf(mapMessage));
        System.out.println("自定义异常处理");
        return param;
    }

    @ExceptionHandler(value = MyException.class)
    Object handleMyException(MyException e, HttpServletRequest request){

        // 进行页面跳转
//        ModelAndView  modelAndView = new ModelAndView();
//        modelAndView.addObject("msg", e.getMessage());
//        modelAndView.setViewName("error.html");
//
//        return modelAndView;

        HashMap param = new HashMap();
        param.put("code", e.getCode());
        param.put("msg", e.getMsg());
        param.put("uri", request.getRequestURI());
        param.put("url", request.getRequestURL());
        return param;
    }
}
